﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using log4net;

namespace Cadence.NET.BaseClasses
{
    /// <summary>
    /// Simple webserver designed to provide health and status to external clients.
    /// </summary>
    /// <see cref="http://www.codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx"/>
    public class Webserver
    {
        #region Private Members

        private readonly HttpListener listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> responderMethod;
        protected static readonly ILog log = LogManager.GetLogger(typeof(CadenceTaskManager));

        #endregion Private Members

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Webserver"/> class.
        /// </summary>
        /// <param name="prefixes">The prefixes.</param>
        /// <param name="method">The method.</param>
        /// <exception cref="System.NotSupportedException">Needs Windows XP SP2, Server 2003 or later.</exception>
        /// <exception cref="System.ArgumentException">
        /// prefixes
        /// or
        /// method
        /// </exception>
        public Webserver(string[] prefixes, Func<HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
                throw new NotSupportedException(
                    "Needs Windows XP SP2, Server 2003 or later.");

            // URI prefixes are required, for example 
            // "http://localhost:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            // A responder method is required
            if (method == null)
                throw new ArgumentException("method");

            foreach (string s in prefixes)
                listener.Prefixes.Add(s);

            responderMethod = method;

            log.InfoFormat("Cadence.NET webserver started. Listening at {0}.", prefixes[0].ToString());

            listener.Start();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Webserver"/> class.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="prefixes">The prefixes.</param>
        public Webserver(Func<HttpListenerRequest, string> method, params string[] prefixes)
            : this(prefixes, method) { }

        #endregion Constructors

        #region Public Methods

        /// <summary>
        /// Runs this instance.
        /// </summary>
        public void Start()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                try
                {
                    while (listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                string rstr = responderMethod(ctx.Request);
                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                            }
                            catch (Exception exc)
                            {
                                log.ErrorFormat("Cadence.NET webserver threw an exception on thread {0}: {1}", Thread.CurrentThread.ManagedThreadId, exc.ToString());
                            }
                            finally
                            {
                                // Always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, listener.GetContext());
                    }
                }
                catch (Exception exc)
                {
                    log.ErrorFormat("Cadence.NET webserver threw an exception on thread {0}: {1}", Thread.CurrentThread.ManagedThreadId, exc.ToString());
                }
            });
        }

        /// <summary>
        /// Stops this instance.
        /// </summary>
        public void Stop()
        {
            listener.Stop();
            listener.Close();
        }

        #endregion Public Methods
    }
}
